import axios from "axios";
// import history from './history'
// antd
import { message } from "antd";
// cookies
import { getToken, getUsername, getDepartment } from "./cookies";

//第一步，创建实例
const service = axios.create({
    baseURL: process.env.REACT_APP_API,
    timeout: 2000000,
});


// 2.请求发出前拦截（请求头）
service.interceptors.request.use(function (config) {
    console.log(config)
    // Do something before request is sent, token username
    config.headers["X-AUTH-TOKEN"] = getToken();
    config.headers["X-AUTH-USER"] = getUsername();
    config.headers["X-AUTH-DEPARTMENT"] = getDepartment();
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});


// 3.响应拦截（响应头）
service.interceptors.response.use(function (response) {
    // Do something with response data
    const data = response.data;
    if(response.status !== 200) { // 全局的错误拦截提示
        message.info(data.msg);
        // 可以针对某些 status 值，进行业务逻辑处理
        if(response.status === 253) {
            console.log('refrush token')
            axios.post('/api/v1/refresh_token').then(res => {
                console.log(res)
            })
            // alert(data)
            // message.error(data)
            window.location.href = '/login'
        }
        if(response.status === 251) {
            // alert(data)
            // message.error(data)
            window.location.href = '/login'
            // history.push('/', {from: history.location})
        }
        return Promise.reject(response)
    } else {  // http状态为200
        return response;
    }
}, function (error) {  // http 状态不为200
    // Do something with response error
    const data = error.request;
    message.error(JSON.parse(data.response).msg)
    return Promise.reject(data);
});

export default service;